﻿using BuyWithoutLoseMoney;
using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;


namespace BuyWithoutLose.Areas.Admin.Controllers
{
    /// <summary>
    /// 产品
    /// </summary>
    [Area("admin")]
    public class ProductController : BaseAdminController
    {
        private readonly IRepository<Product,int> _productRepository;
        private readonly IRepository<ProductType,int> _productTypeRepository;
        private readonly IRepository<ProductPic,int> _productPicRepository;
        private readonly IHostingEnvironment _hostingEnvironment;

        public ProductController(IRepository<Product,int> productRepository,IHostingEnvironment hostingEnvironment
            , IRepository<ProductType, int> productTypeRepository
            , IRepository<ProductPic, int> productPicRepository, BuyWithoutLoseMoneyDBContext db) : base(db)
        {
            _productRepository = productRepository;
            _hostingEnvironment = hostingEnvironment;
            _productTypeRepository = productTypeRepository;
            _productPicRepository = productPicRepository;

        }
        #region 产品列表，查询，修改，删除
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var products = await _productRepository.GetAllListAsync();
            var PType = await _productTypeRepository.GetAllListAsync();
            var Ppic = await _productPicRepository.GetAllListAsync();
            ViewBag.PType = PType;
            ViewBag.Ppic = Ppic;
            return View(products);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="Name">产品名称</param>
        /// <param name="ProductTypeId">分类Id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Index(int page, int limit, string Name, int ProductTypeId = 0)
        {
            var product = await _productRepository.GetAllListAsync();
            var query = product.Where(x => true);
            if (!string.IsNullOrEmpty(Name))
            {
                query = query.Where(x => x.Title.Contains(Name));
            }
            //if (ProductTypeId != 0)
            //{
            //    query=query.Where(x=>x.Produc==ProductTypeId)
            //}
            var count = query.Count();
            var list = query.OrderBy(x => x.Id).Skip((page - 1) * limit).Take(limit).ToList()
               .Select(x => new
               {
                   id = x.Id,
                   title = x.Title,
                   subtitle = x.SubTitle,
                   price = x.Price,
                   brand = x.Brand,
                   createtime = x.CreateTime.ToString(),
                   deltime = x.DelTime.ToString(),
                   status = x.Status,
                   describe = x.Describe,
                   //产品图片
                   //产品分类

               });
            return Json(new { Code = 0, Msg = "", Data = list, Count = count });

        }
        /// <summary>
        /// 添加产品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Create()
        {
            var type = await _productTypeRepository.GetAllListAsync();
            ViewBag.Type = type;
            var pic = await _productPicRepository.GetAllListAsync();
            ViewBag.Pic = pic;
            var pro = await _productRepository.GetAllListAsync();
            ViewBag.Pro = pro;
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Create(Product product)
        {
            if (ModelState.IsValid)
            {
                await _productRepository.InsertAsync(product);
                return Json(new { isSuccess = true, msg = "添加成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "添加失败，请重试！" });
        }
        /// <summary>
        /// 产品的修改
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            var type = await _productTypeRepository.GetAllListAsync();
            ViewBag.Type = type;
            var pic = await _productPicRepository.GetAllListAsync();
            ViewBag.Pic = pic;
            var pro = await _productRepository.GetAllListAsync();
            var p = pro.FirstOrDefault(x => x.Id == id);
            return View(p);
        }
        [HttpPost]
        public async Task<IActionResult> Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                await _productRepository.UpdateAsync(product);
                return Json(new { isSuccess = true, msg = "修改成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "修改失败，请重试！" });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Del(int id)
        {
            Product p = new Product() { Id = id };
            if (ModelState.IsValid)
            {
                await _productRepository.DeleteAsync(p);
                return Json(new { isSuccess = true, msg = "删除成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "删除失败，请重试！" });
        }
        /// <summary>
        /// 图片显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ProPic(int id)
        {
            var pro = _productRepository.GetAllList();
            var p = pro.FirstOrDefault(x => x.Id == id);
            var pic = _productPicRepository.GetAllList();
            ViewBag.Pic = pic;
            return View(p);
        }
        #region
        //public IActionResult Upload(IFormFile file)
        //{

        //    if (file != null && file.Length > 0)
        //    {
        //        // 生成图片保存的路径和文件名
        //        var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
        //        if (!Directory.Exists(path))
        //        {
        //            Directory.CreateDirectory(path);
        //        }
        //        var filename = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
        //        var filepath = Path.Combine(path, filename);

        //        // 保存图片到指定路径
        //        using (var stream = new FileStream(filepath, FileMode.Create))
        //        {
        //            file.CopyTo(stream);
        //        }
        //        // 将图片数据返回给前端
        //        return Json(new
        //        {
        //            code = 0,
        //            data = new
        //            {
        //                src = "/admin/product/uploads/" + filename,
        //                filename = filename
        //            }
        //        });
        //    }
        //    else
        //    {
        //        // 上传失败
        //        return Json(new
        //        {
        //            code = -1,
        //            msg = "上传失败"
        //        });
        //    }
        //}
        //[HttpPost]
        //public async Task<IActionResult> Save(string src, string filename)
        //{
        //    // 将图片数据保存到数据库中
        //    // ...
        //    var Pic = new ProductPic
        //    {
        //        PicAddress = src,
        //        Describle = filename,
        //    };
        //    await _productPicRepository.InsertAsync(Pic);
        //    // 返回保存结果给前端
        //    return Json(new
        //    {
        //        code = 0,
        //        msg = "保存成功"
        //    });
        //}
        #endregion
        #endregion        

    }
}